package com.quotes.charts;

import java.awt.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

import com.quotes.Configuration;
import com.quotes.Parameters;
import com.quotes.datamodell.*;

public class PortfolioChart extends JPanel
{
	private Logger logger = Logger.getLogger(getClass().toString());
	private static final long serialVersionUID = 1L;
	private TimeSeries value = null;
	private Parameters parameters = null;
	
	public PortfolioChart(TimeSeries value, Parameters parameters) {
		this.value = value;
		this.parameters = parameters;
		this.createChart();
		
        logger.debug("PortfolioChart created!");
	}
	
	protected void createChart() {
		XYDataset xyDataset = createXyDataset();
        DateAxis domainAxis = createDateAxis();
        NumberAxis rangeAxis = createNumberAxis();
    	XYPlot plot = new XYPlot(xyDataset, domainAxis, rangeAxis, new XYLineAndShapeRenderer(true, false));
    	addMarker(plot);
		JFreeChart chart = new JFreeChart(plot);
		ChartPanel panel = new ChartPanel(chart);
		this.setLayout(new BorderLayout());
        this.add(panel, BorderLayout.CENTER);
	}
	
	private NumberAxis createNumberAxis() {
		NumberAxis rangeAxis = new NumberAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
        rangeAxis.setRange(value.getMinValue() * .95, value.getMaxValue() + 1.05);
		return rangeAxis;
	}

	private DateAxis createDateAxis() {
		DateAxis domainAxis = new DateAxis();
        domainAxis.setAutoRange(true);
        domainAxis.setTickLabelsVisible(true);
        domainAxis.setAutoTickUnitSelection(true);
		return domainAxis;
	}
	    
	private XYDataset createXyDataset() {
		TimeSeriesCollection data = new TimeSeriesCollection();
    	data.addSeries(value.convertToChartTimeSeries("PortfolioValue"));
		return data;
	}
	
	private void addMarker(XYPlot plot) {
        final Marker marker = new ValueMarker(parameters.getAsDouble("initialCash"));
        marker.setPaint(Color.green);
        marker.setLabel("Start value");
        plot.addRangeMarker(marker);
    }
}
